import * as LOCAL_API from './local.js'
import * as NETWORK_API from './network.js'
import store from '@/store/index.js'
import config from '@/common/config.js'
import {
	DATA_LOCATION_TYPE,
	SYNC_STATUS_TYPE,
	ARCHIVES_TYPE
} from '@/const/archives/index.js'
import {
	convertToTimestamp
} from '@/utils/index.js'
import timeFormat from '@/uview-ui/libs/function/timeFormat.js'
// 设置环境变量
let environment = store.getters.isNetworkConnected ? "network" : "local"; // 默认为本地环境

store.subscribe((mutation, state) => {
	if (mutation.type === 'SET_IS_CONNECTED') {
		if (environment !== (store.getters.isNetworkConnected ? "network" : "local")) {
			environment = store.getters.isNetworkConnected ? "network" : "local";
			getArchivesListByEnvironment({}, true)
		}
	}
});

const {
	NOT_UPWARD_SYNCED,
	PENDING_UPWARD_UPDATE,
	NOT_DOWNWARD_SYNCED,
	PENDING_DOWNWARD_UPDATE,
	SYNCED
} = SYNC_STATUS_TYPE
const {
	LOCAL,
	REMOTE
} = DATA_LOCATION_TYPE

// 获取 所有案卷类型对应的模块列表 存储到 基础信息 内
export async function getModulesListToBasicData() {
	let archivesTypeList = {}
	// getArchivesTypes 中 已经默认按照 项目const声明的案卷类型 顺序去请求
	const responseArr = await NETWORK_API.getArchivesTypes()
	Object.values(ARCHIVES_TYPE).forEach(id => {
		if (responseArr[id] && responseArr[id].data) {
			archivesTypeList[id] = responseArr[id].data.map(item => {
				return {
					name: item.dictLabel,
					value: item.dictValue,
					remark: item.remark,
				}
			})
		}
	})
	return archivesTypeList
}

// 在线登录过后，存储 user信息 到本地
export async function getUserInfoToBasicData(userInfo) {
	const vuex_basicData = store.state.vuex_basicData
	let userInfoList = vuex_basicData.userInfoList || []
	const index = userInfoList.findIndex(item => item.userId == userInfo.userId)
	if (index === -1) {
		userInfoList.push(userInfo)
	}
	return userInfoList
}

/*
	列表融合逻辑：
	1. 给每个案卷、模块 在新增时添加 md5 标识，
	2. app.vue 中 获取 案卷基础信息（其中包括案卷列表、用户信息、正好信息等其他数据）
	保存为全局变量，然后在多处使用。
*/
// 获取案卷列表
export async function getArchivesListByEnvironment(params, refresh = false, remoteList = []) {
	const networkP = environment === "network" ? NETWORK_API.getListFromNetwork(params) : new Promise(resolve =>
		resolve([]))

	// #ifdef APP-PLUS
	const pArr = [LOCAL_API.getListLocally(), networkP];
	// #endif
	// #ifdef H5
	const pArr = [new Promise(resolve => resolve([])), networkP];
	// #endif
	const [localData, networkData] = await Promise.all(pArr);
	remoteList = store.getters.isNetworkConnected ? networkData : remoteList
	const localArr = (localData || []).filter(item => item.md5 !== null).map(item => ({
		...item,
		localStatus: LOCAL
	}))
	const remoteArr = remoteList.filter(item => item.md5 !== null).map(item => ({
		...item,
		localStatus: REMOTE
	}))
	const mergedArray = mergeAndDeduplicateArrays(localArr, remoteArr)
	return mergedArray
}

/**
 * @param {Array} localArr
 * @param {Array} remoteArr
 * @returns {Array}
 * @description 合并本地列表与云端列表数据，然后 添加 同步状态 */
function mergeAndDeduplicateArrays(localArr, remoteArr) {
	const loghtCopyLocalArr = JSON.parse(JSON.stringify(localArr))
	let mergedArray = remoteArr.reduce((result, currentItem) => {
		if (currentItem.md5 !== undefined && currentItem.md5 !== null) {
			const existingIndex = result.findIndex(item => item.md5 === currentItem.md5);
			// 检查当前项的 md5 是否在 result 中已存在
			if (existingIndex === -1) {
				result.push(currentItem);
			} else {
				let localUpdateTime = convertToTimestamp(result[existingIndex].updateTime),
					remoteUpdateTime = convertToTimestamp(currentItem.updateTime);
				// ↑待更新
				if (localUpdateTime > remoteUpdateTime) {

					result[existingIndex].pullUpdateTime = result[existingIndex].pullUpdateTime
					result[existingIndex].pushUpdateTime = result[existingIndex].pushUpdateTime
					result[existingIndex].updateTime = localUpdateTime
				} // ↓待更新
				else if (localUpdateTime < remoteUpdateTime) {
					// result[existingIndex] = currentItem
					result[existingIndex].pullUpdateTime = currentItem.pullUpdateTime
					result[existingIndex].pushUpdateTime = remoteUpdateTime
					result[existingIndex].updateTime = localUpdateTime
				}
				// result[existingIndex].updateTime = localUpdateTime > remoteUpdateTime ? localUpdateTime :
				// 	remoteUpdateTime
			}
		}
		return result
	}, loghtCopyLocalArr)
	mergedArray = mergedArray.map(item => calculateSyncStatus(item, localArr, remoteArr)) // 处理同步逻辑

	mergedArray.sort((itemA, itemB) => {
		const itemATime = convertToTimestamp(itemA.createTime)
		const itemBTime = convertToTimestamp(itemB.createTime)
		return itemBTime - itemATime
	})
	return mergedArray
}
/** @description 处理同步状态 */
function calculateSyncStatus(item, localArr, remoteArr) {
	let isSyn = item.localStatus,
		pullUpdateTime = convertToTimestamp(item.pullUpdateTime),
		pushUpdateTime = convertToTimestamp(item.pushUpdateTime),
		updateTime = convertToTimestamp(item.updateTime)
	let syncStatus = calculateSyncStatusBasedOnTimestamps(updateTime, pullUpdateTime, pushUpdateTime, isSyn);
	// 封装重复逻辑到单独的函数
	syncStatus = updateSyncStatusBasedOnArrays(syncStatus, item, remoteArr, true);
	syncStatus = updateSyncStatusBasedOnArrays(syncStatus, item, localArr, false);
	return {
		...item,
		syncStatus
	}
}
/**
 * 根据时间戳计算同步状态
 */
function calculateSyncStatusBasedOnTimestamps(updateTime, pullUpdateTime, pushUpdateTime, isSyn) {
	if (!pullUpdateTime && !pushUpdateTime) { // 未同步
		return isSyn ? NOT_UPWARD_SYNCED : NOT_DOWNWARD_SYNCED;
	} else if (updateTime < pushUpdateTime) { // 待下载更新
		return PENDING_DOWNWARD_UPDATE;
	} else if (updateTime > pullUpdateTime) { // 待上传更新
		return PENDING_UPWARD_UPDATE;
	} else { // 已同步
		return SYNCED;
	}
}
/**
 * 根据数组检查更新同步状态
 */
function updateSyncStatusBasedOnArrays(syncStatus, item, arr, isRemote) {
	let set = new Set(arr.map(rItem => rItem.md5));
	let flag = set.has(item.md5);
	// 如果在线上或本地被删除了，更新同步状态
	if ([PENDING_UPWARD_UPDATE, PENDING_DOWNWARD_UPDATE, SYNCED].includes(syncStatus) && !flag) {
		return isRemote ? NOT_UPWARD_SYNCED : NOT_DOWNWARD_SYNCED;
	}
	return syncStatus;
}

// 获取 最新案卷\指定案卷
export async function getArchivesDetailByEnvironment(archivesId) {
	let remoteArchivesList = !store.getters.isNetworkConnected ? store.state.vuex_basicData.remoteArchivesList : []
	// const archivesList = await getArchivesListByEnvironment({}, false, remoteArchivesList)
	// #ifdef H5
	const archivesList = await getArchivesListByEnvironment({}, false, remoteArchivesList)
	// #endif

	// #ifdef APP-PLUS
	const allArchivesList = await getArchivesListByEnvironment({}, false, remoteArchivesList)
	const archivesList = allArchivesList.filter(item => item.localStatus == LOCAL)
	// #endif
	if (!archivesList.length) return null
	if (archivesId) {
		const item = archivesList.find(item => item.archivesId == archivesId)
		return item
	} else {
		return archivesList[0]
	}
}

/**
 * 获取 案卷的模块列表
 * @param {Object} params - 获取列表的必须参数
 * @param {string|number} params.archivesId - 案卷id
 * @param {string|number} params.archivesType - 案卷类型
 * @param {string|number} params.syncStatus - 案卷的同步状态
 */
export async function getModulesListFromArchive(params) {
	const {
		archivesId,
		archivesType,
		syncStatus
	} = params
	if (syncStatus != NOT_DOWNWARD_SYNCED) {
		let res = await LOCAL_API.getModulesListLocally(archivesId, archivesType)
		return res
	} else {
		return Promise.reject(new Error('请先将案卷数据同步到本地'))
	}
}

/**
 * 获取 所有证据链列表
 * @param {Object} params - 获取列表的必须参数
 * @param {string|number} params.archivesId - 案卷id
 * @param {string|number} params.archivesType - 案卷类型
 * @param {string|number} params.syncStatus - 案卷的同步状态
 */
export async function getEvidenceChainListFromArchive(params) {
	const {
		archivesId,
		archivesType,
		syncStatus
	} = params

	if (syncStatus != NOT_DOWNWARD_SYNCED) {
		let res = await LOCAL_API.getEvidenceChainListLocally(archivesId, archivesType)
		return res
	} else {
		return Promise.reject(new Error('请先将案卷数据同步到本地'))
	}
}

/**
 * 获取 所有词典数据
 */
export async function getDictData() {
	const dictArr = ['video_category', 'resource_type', 'tag_type', 'person_type'];
	const dictKeyArr = ['category', 'resource', 'tag', 'inquiryTargets'];

	const pArr = dictArr.map(item => NETWORK_API.getDictdataFormNetwork(item));

	const res = await Promise.allSettled(pArr);

	const dictObj = {};

	res.forEach((item, index) => {
		const key = dictKeyArr[index];
		if (item.status === 'fulfilled') {
			dictObj[key] = item.value.data.map(cItem => ({
				label: cItem.dictLabel,
				value: cItem.dictValue
			}));
		}
	});

	return dictObj;
}


export async function getAllUserList() {
	const result = await NETWORK_API.getUserListFormNetwork({
		pageNum: 1,
		pageSize: 20
	})
	return result.rows
}

export async function getTempleteList() {
	const data = await NETWORK_API.getTempleteListFormNetwork()
	return data.rows
}